package com.zc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zc.component.EntityFile;
import com.zc.entity.Fileer;
import com.zc.entity.Filepath;
import com.zc.mapper.FileerMapper;
import com.zc.mapper.FilepathMapper;
import com.zc.util.FileUtil;
import com.zc.util.Uzip;
import com.zc.util.zipUncompress;
//import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FileController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    EntityFile entityFile;
    @Autowired
    FilepathMapper filepathMapper;
    @Autowired
    FileerMapper fileerMapper;

    @ResponseBody
    @GetMapping("auditing/{id}")
    public String auditing(@PathVariable("id") int id) {

        return "success";
    }

    @ResponseBody
    @PostMapping("shenhe/{id}")
    public String shenHe(@PathVariable("id") int id, @RequestBody String jsonParam, HttpSession session) {
        int teamid = (int) session.getAttribute("teamid");
        logger.info(jsonParam.toString());

        JSONObject jo = JSON.parseObject(jsonParam.toString());
        String shenhe = (String) jo.get("why");
        Fileer file = new Fileer();
        file.setId(id);
        file.setSenhe(3);
        file.setShenhefactor(shenhe);
        fileerMapper.updateByPrimaryKeySelective(file);
        Fileer fileer = fileerMapper.selectByPrimaryKey(id);
        FileUtil.deleteDir(entityFile.getBetweenRepository() + teamid + "/" + fileer.getName());
        logger.info(shenhe);
        return "success";
    }

    @ResponseBody
    @GetMapping("shenhe/{id}")
    public String shenHetongguo(@PathVariable("id") int id, HttpSession session)

    {
        int teamid = (int) session.getAttribute("teamid");
        Fileer fileer = fileerMapper.selectByPrimaryKey(id);

        String oldpath = entityFile.getBetweenRepository() + teamid + "/";
        String filepath = filepathMapper.selectByPrimaryKey(fileer.getFilepath()).getName();
        String newpath = entityFile.getRepository() + teamid + "/" + filepath + "/";
        FileUtil.copy(oldpath, newpath, fileer.getName());
        logger.info("审核成功接口");
        Fileer maxfile = fileerMapper.selectMaxIdByName(fileer.getName(), teamid, fileer.getFilepath());
        if (maxfile == null) {
            fileer.setFlag("1");
            fileer.setEdition("1");
        } else if (maxfile.getEdition2() == 1) {
            String a=maxfile.getEdition()+".1";
            logger.info("进入分支累加"+a);
            fileer.setEdition(a);
            maxfile.setFlag("0");
            fileer.setFlag("1");
            fileerMapper.updateByPrimaryKeySelective(maxfile);
        } else if (maxfile.getEdition2() != 1) {
            logger.info("进入版本累加");
            String banben = maxfile.getEdition();
            int a = banben.lastIndexOf(".");
            logger.info("打印" + a);
            if (a == -1) {
                String no = maxfile.getEdition();
                int no1 = Integer.parseInt(no) + 1;
                logger.info("累加后版本" + no1);
                fileer.setEdition(Integer.toString(no1));
                maxfile.setFlag("0");
                fileer.setFlag("1");
                fileerMapper.updateByPrimaryKeySelective(maxfile);

            } else {
                String no = maxfile.getEdition().substring(a + 1);
                int no1 = Integer.parseInt(no) + 1;
                String no2 = maxfile.getEdition().substring(0, a) + "." + no1;
                fileer.setEdition(no2);
                maxfile.setFlag("0");
                fileer.setFlag("1");
                logger.info("累加后版本" + no1);
                fileerMapper.updateByPrimaryKeySelective(maxfile);
            }

        }
        fileer.setSenhe(1);
        fileerMapper.updateByPrimaryKeySelective(fileer);

        String newpath1 = entityFile.getBackupsRepository() + teamid + "/" + fileer.getEdition() + "/"+filepath+"/";
       // FileUtil.copy(oldpath, newpath1, fileer.getName());
        try {
            Uzip.zip(oldpath+"/"+fileer.getName(),newpath1+"/"+fileer.getName()+".zip",fileer.getName());
            logger.info("压缩成功************" );
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileUtil.deleteDir(oldpath);
        return "success";
    }

    @GetMapping("filelist01")
    public String fileList(Model model) {
        model.addAttribute("filepath", filepathMapper.selectAll());
        return "file/filelist";
    }

    @ResponseBody
    @GetMapping("filelist/{filepath}")
    public List<Fileer> fileList(@PathVariable("filepath") int filepath, HttpSession session) {
        int teamid = (int) session.getAttribute("teamid");
        List list = null;
        if (filepath == 0) {
            list = fileerMapper.selectByTeam(teamid);
        } else {
            list = fileerMapper.selectByTeamAndFilePath(teamid, filepath);
        }

        return list;
    }

    @ResponseBody
    @PostMapping("addfilepath")
    public String addfilepath(@RequestBody String jsonParam, HttpSession session) {
        int teamid = (int) session.getAttribute("teamid");
        logger.info(jsonParam.toString());

        JSONObject jo = JSON.parseObject(jsonParam.toString());
        String filepathname = (String) jo.get("why");
        Filepath filepath = new Filepath();
        filepath.setName(filepathname);
        filepath.setTeamid(teamid);
        filepathMapper.insertSelective(filepath);
        return "success";
    }

    @GetMapping("/rizhi")
    public String rizhi(@RequestParam("name") String name, @RequestParam("filepath") int filepath, HttpSession session, Model model) {
        int teamid = (int) session.getAttribute("teamid");
        /*List filelist =fileerMapper.selectForRiZhi(name,filepath,teamid);
        model.addAttribute("filelist",filelist);*/
        return "file/rizhi";
    }

    @ResponseBody
    @PostMapping(value="/rizhilist")
    public List rizhilist(@RequestBody String jsonParam, HttpSession session) {
        int teamid = (int) session.getAttribute("teamid");
        /*List filelist =fileerMapper.selectForRiZhi(name,filepath,teamid);
        model.addAttribute("filelist",filelist);*/

        logger.info(jsonParam.toString());

        JSONObject jo = JSON.parseObject(jsonParam.toString());
        int id = 0;

            id = Integer.parseInt((String) jo.get("name"));
        Fileer fileer = fileerMapper.selectByPrimaryKey(id);
        String name =fileer.getName();
        String filepath = null;

            filepath =  (String) jo.get("filepath");

        List filelist = fileerMapper.selectForRiZhi(name, filepath, teamid);
        return filelist;
    }

    @ResponseBody
    @GetMapping("/myfilelist")
    public List myfilelist(HttpSession session) {
        String myname = (String) session.getAttribute("loginUser");
        /*List filelist =fileerMapper.selectForRiZhi(name,filepath,teamid);
        model.addAttribute("filelist",filelist);*/
        int teamid = (int) session.getAttribute("teamid");


        List filelist = fileerMapper.selectByUpName(myname, teamid);
        return filelist;
    }

    @ResponseBody
    @PostMapping("/huituifile")
    public String huituifile(@RequestBody String jsonParam, HttpSession session) {
        int teamid = (int) session.getAttribute("teamid");
        logger.info(jsonParam.toString());

        JSONObject jo = JSON.parseObject(jsonParam.toString());
        String name = (String) jo.get("name");
        String edition = (String) jo.get("edition");
        int filepath =Integer.parseInt ((String) jo.get("filepath"));
        Fileer maxfile = fileerMapper.selectMaxIdByName(name,teamid,filepath);
        Fileer fileer=fileerMapper.selectByName(name,teamid,filepath,edition);
        maxfile.setFlag("0");
        fileer.setFlag("1");
        fileer.setEdition2(1);
        fileerMapper.updateByPrimaryKeySelective(fileer);
        fileerMapper.updateByPrimaryKeySelective(maxfile);
        String filepathname = filepathMapper.selectByPrimaryKey(fileer.getFilepath()).getName();
        String newpath = entityFile.getRepository() + teamid + "/" + filepathname + "/";
        String oldpath = entityFile.getBackupsRepository() + teamid + "/" + fileer.getEdition() + "/"+filepathname+"/";
        //FileUtil.copy(oldpath, newpath, fileer.getName());
        try {
            zipUncompress.zipUncompress(oldpath+"/"+fileer.getName()+".zip",newpath+"/");
        } catch (Exception e) {
            e.printStackTrace();
        }


        return "success";
    }
}
